<?php

namespace App\Common\Enums;

use App\Common\Enums\Attributes\DesAttribute;
use App\Common\Enums\Attributes\TagAttribute;
use JetBrains\PhpStorm\ExpectedValues;
use Sc\Util\HtmlElement\El;
use Sc\Util\HtmlElement\ElementType\AbstractHtmlElement;
use Sc\Util\HtmlStructure\Tag;

trait EnumStatusTrait
{
    public static function values(): array
    {
        return array_map(fn($enum) => $enum->value, self::cases());
    }

    /**
     * @param bool  $isKeyValuePair
     * @param array $disabledValue
     *
     * @return array
     */
    public static function mapping(bool $isKeyValuePair = false, array $disabledValue = []): array
    {
        $mapArr = [];
        foreach (self::cases() as $enumMapT) {
            $content = $enumMapT->getDes();
            $isKeyValuePair
                ? $mapArr[$enumMapT->value] = $content
                : $mapArr[] = ['value' => $enumMapT->value, 'label' => $content, 'disabled' => in_array($enumMapT->value, $disabledValue)];
        }
        return $mapArr;
    }


    /**
     * 所有的标签html代码
     *
     * @return AbstractHtmlElement[]|array
     *
     * @author chenlong<vip_chenlong@163.com>
     * @date   2022/5/19 18:00
     */
    public static function tagMapping(): array
    {
        array_map(function ($enum) use (&$mapping) {
            return $mapping[$enum->value] = $enum->toTag();
        }, self::cases());

        return $mapping;
    }

    /**
     * @param string $type
     * @param string $theme
     *
     * @return AbstractHtmlElement
     * @deprecated 不推荐使用，请使用 toTag 方法
     */
    private function getTag(string $type = '', #[ExpectedValues(['light', 'dark', 'plain'])] string $theme = 'light'): AbstractHtmlElement
    {
        $template = '<el-tag class="ml-2" size="small" type="success"></el-tag>';

        return El::fromCode($template)->setAttrs([
            'effect' => $theme,
            'type'   => $type,
        ])->append($this->getDes());
    }

    /**
     * 获取明细
     *
     * @return mixed
     */
    public function getDes(): mixed
    {
        $reflectionClass = new \ReflectionEnumUnitCase($this, $this->name);

        if ($reflectionClass->getAttributes(DesAttribute::class)) {
            return $reflectionClass->getAttributes(DesAttribute::class)[0]->newInstance()->value;
        }
        return $this->name;
    }

    /**
     * @return AbstractHtmlElement|string
     */
    public function toTag(): AbstractHtmlElement|string
    {
        $reflectionClass = new \ReflectionEnumUnitCase($this, $this->name);

        $template = Tag::create($this->getDes());

        if ($tagAttributes = $reflectionClass->getAttributes(TagAttribute::class)) {
            /** @var TagAttribute $tagAttribute */
            $tagAttribute = $tagAttributes[0]->newInstance();
            $template->setAttrs([
                'type'  => $tagAttribute->type,
                'theme' => $tagAttribute->theme,
            ]);
        }
        return $template->render();
    }
}
